package m.toolkit.codegenerator;

import java.io.File;

import m.framework.controller.BaseController;
import m.framework.exception.SystemException;
import m.framework.template.TemplateUtil;
import m.framework.utils.FileUtil;
import m.framework.utils.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CodeGenerator {
	private static Logger log = LoggerFactory.getLogger(CodeGenerator.class);
	public static enum PageType{
		index,query,prepareInsert,prepareUpdate,view;
		
		public String tempate(){
			return Config.TEMPLATE_DIR+"/"+this.toString()+".vm";
		}	
	}
	
	public static void createAll(Class controller){
		createAll(controller,false);
	}
	
	private static String jspDir(Class controllerClaz){
		String dir=controllerClaz.getPackage().getName().replace(m.Config.PACKAGE_ROOT, "");
		String modelName=controllerClaz.getSimpleName().replaceAll("Controller$", "");
		dir=dir.replaceAll("controller$", "")+"/"+StringUtil.firstLower(modelName);
		return dir.replaceAll("\\.", "/");
	}
	
	//创建默认页面,如果idnex页存在就认为已经创建了跳过
	public static void createAll(Class controllerClaz,boolean override){
		String templatePath=jspDir(controllerClaz);
		String indexName=Config.JSP_DIR+"/"+templatePath+"/"+PageType.index+".jsp";
		
		File file=new File(indexName);
		if(file.exists()&&!override){
			return;
		}
		for(PageType type:PageType.values()){
			String templateText=TemplateUtil.getTemplateText(type.tempate());
			if(StringUtil.isEmpty(templateText)){
				throw new SystemException("模板内容为空:"+type.tempate());
			}
			String fileName=Config.JSP_DIR+"/"+templatePath+"/"+type+".jsp";
			String text=TemplateUtil.getText( templateText, new ModelConfig(controllerClaz));
			String f=FileUtil.createFile(fileName, text);
			log.debug("创建文件:"+f);
		}
	}
	
	public static String getPage(BaseController controller,PageType type){
		String text=TemplateUtil.getTemplateText(type.tempate());
		return TemplateUtil.getText(text,new ModelConfig(controller.getClass()));
	}

}
